/**
 * COPYRIGHT (C) 2008 Erica Margetich and Loc Phan 
 * To create a cipher that substitutes letters in a message
 * @author Erica Margetich
 * @author Loc Phan
 * @version 1.01 2008-12-07
 */

package edu.sjsu.cs.security;

public class SubstitutionCipher implements MessageEncoder, MessageDecoder
{
   /**
    * Constructs a Substitution Cipher
    * @param shift the amount of times each letter shifts
    */
   public SubstitutionCipher(int shift)
   {
      ShiftKey = shift;
   }
   /**
    * Returns the encoded message
    * @param plaintext the message to be encoded
    * @return the message after each letter is shifted
    */
   public String encode(String plaintext)
   {
      char myCharArray[] = plaintext.toCharArray();
      for(int i=0;i<plaintext.length();i++)
      {
         myCharArray[i] = shiftCharForward(myCharArray[i]);
        
      }
    
      return new String(myCharArray);
      
   }

   /**
    * Returns the decoded message
    * @param cipherText the message to be decoded
    * @return the message after each letter has been shifted
    */
   public String decode(String cipherText)
   {
      char myCharArray[] = cipherText.toCharArray();
      for(int i=0;i<cipherText.length();i++)
      {
         myCharArray[i] = shiftCharBackward(myCharArray[i]);
      }
    
      return new String(myCharArray);
   }
   
   /**
    * Shifts the characters forward
    * @param aChar the character being shifted forward
    * @return the character after it has been shifted
    */
   private char shiftCharForward(char aChar)
   {
     int result = (int) aChar;
     result+=ShiftKey;
     return (char)result;
   }
   
   /**
    * Shifts the characters backward
    * @param aChar the character being shifted backward
    * @return the character after it has been shifted
    */
   private char shiftCharBackward(char aChar)
   {
      int result = (int) aChar;
      result-=ShiftKey;
      return (char)result;
   }
   
   //private instance field
   private int ShiftKey;
}
